import unittest

import requests
from ddt import ddt, data
from Tools.do_excel import DoExcel
from Tools.Get_Cookies import GetData
from Tools.HTTPRequestV1 import HTTPRequest
from Tools.get_path import *
from Tools.log import MyLog
import warnings
from Tools.do_mysql import DoMysql

test_data = DoExcel.get_data(test_case_path)  # 执行所有登录的用例

test_result = 0
cookie =None

@ddt
class TestHTTPRequests(unittest.TestCase):
    def setUp(self):
        print(f"开始执行用例")
        # 解决warnings.simplefilter('ignore', ResourceWarning错误
        warnings.simplefilter('ignore', ResourceWarning)

    ###NMB版本
    @data(*test_data)
    def test_api(self, item):
        global test_result
        global cookie
        print(f"正在执行第{item['case_id']}个用例，用例名称是：{item['title']}")
        # 如果是列表嵌套列表，读数据就用索引方式；列表嵌套字典，就用key的方式来读
        sess_obj = requests.Session()
        response = sess_obj.post(url='https://openapiv5.ketangpai.com//UserApi/login',
                                 data='{"email": "790874262@qq.com", "password": "beiaidigan123!", "remember": "0"}')
        # res_obj = HTTPRequest().test_api(item['url'], item['data'], item['http_method'], getattr(GetData, 'cookie'))
        res_obj = HTTPRequest().test_api(item['url'], item['data'], item['http_method'], cookie=response.cookies)
        # MyLog().info(f"获取到的请求数据是：{item['data']}")
        # if item['check_sql']!=None:
        #     MyLog().info(f"此条用例需要做数据库校验：{item['title']}")
        #     query_sql = item['check_sql']['sql']

        # MyLog().info('-----开始http请求，接口请求——---------')
        # if item['sheet name '] in getattr(GetData,'check_list'):
        #     query_sql = f'select product_price from product where product_category_id{}'
        #     Before_Amount = DoMysql().do_mysql(query_sql,1)[0]
        #     data = {"product_category_id":"${nomal}"}
        #     #在去请求之前http
        #     res =  TestHTTPRequests.test_api(item['data'],item['data'],item['http_method'])
        #     #请求之后检查值
        #     query_sql = 'select product_price from product where product_category_id{}'
        #     After_Amount=DoMysql().do_mysql(query_sql,1)[0]
        #
        #     if abs(Before_Amount-After_Amount)==eval(item['data'])['amount']:
        #         check_res  = '金额正确'
        #     else:

        if res_obj.cookies:
            setattr(GetData, 'cookie', res_obj.cookies)
        try:
            self.assertEqual(item['expected'], res_obj.json()['code'])
            test_result = 'PASS'
        except AssertionError as e:
            # 定义结果属性
            test_result = 'Fail'
            # 写入结果
            # 处理所有响应异常，引入日志收集类
            MyLog().error(f"响应过程中发现异常：{e}")
            raise e
        except PermissionError as e:
            MyLog().error(f"文件拒绝写入：{e}")
        except IOError as e:
            MyLog().error(f"发现IO异常：{e}")

        finally:
            DoExcel.write_result_data(test_case_path, item['sheet_name'], item['case_id'] + 1, str(res_obj.json()),
                                      test_result)
            MyLog().info(f"请求结果是：{res_obj.json()}")
            print(res_obj.json())


def tearDown(self):
    print(f"结束执行用例")
